package nettyProtocol.serverAndClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import nettyProtocol.code.NettyMessageDecoder;
import nettyProtocol.code.NettyMessageEncoder;
import nettyProtocol.handshakeAndAuthentication.LoginAuthReqHandler;
import nettyProtocol.pojo.NettyMessage;
import nettyProtocol.wather.HeartBeatReqHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public abstract class NettyClient {
    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    EventLoopGroup group = new NioEventLoopGroup();

    //与服务端连接的管道
    private Channel channel;

    public synchronized void connect(int port,String host){
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ClientChildChannelHandler());

            ChannelFuture f = b.connect(host, port).sync();
            this.channel = f.sync().channel();
//            f.channel().closeFuture().sync();
        } catch (Exception e){
            System.out.println("断线重连开始");
            executor.execute(new Runnable() {
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                        try {
                            connect(9000,"127.0.0.1");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public abstract void initChannel(ChannelPipeline pipeline);

    /**
     * 字类可以覆盖写
     * @throws Exception
     */
    protected void initChannel0(ChannelPipeline pipeline) {
        this.initChannel(pipeline);
    }


    /**
     * 断开连接，释放资源
     */
    public synchronized void disConnect() {
        if (channel != null) {
            //关闭管道
            channel.closeFuture();
            channel.close();
            channel = null;
            //关闭线程组
            group.shutdownGracefully();
        }
    }

    /***
     * 发送数据给服务端
     * @throws Exception
     */
    public void sendData(final NettyMessage message) throws Exception {
        if (channel != null && channel.isActive()) {
            System.out.println("client send message");
            channel.writeAndFlush(message);
        }
    }

    public class ClientChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected  void initChannel(SocketChannel ch) throws Exception {
            //解码器
            ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4, -8, 0));
            //编码
            ch.pipeline().addLast(new NettyMessageEncoder());
            ch.pipeline().addLast(new ReadTimeoutHandler(50));
            //登录请求
            ch.pipeline().addLast(new LoginAuthReqHandler());
            //心跳连接
            ch.pipeline().addLast(new HeartBeatReqHandler());
            initChannel0(ch.pipeline());
        }
    }

//    public static void main(String[] args) throws Exception {
//        NettyClient client =  new NettyClient();
//        client.connect(9000,"127.0.0.1");
//
//        NettyMessage message = new NettyMessage();
//        Header header = new Header();
//        header.setType((byte)1);
//        header.setSessionID(100L);
//        message.setHeader(header);
//        message.setBody("客户端发送的消息");
//        client.sendData(message);
//
////        client.disConnect();
//    }
}
